package su.msk.jet.team01.chatik.server.commands.authorized;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import su.msk.jet.team01.chatik.server.data.Client;
import su.msk.jet.team01.chatik.server.exception.InvalidArgumentException;

public class SendMessageCommand extends AuthorizedCommand {

	private static final String MESSAGE_PATTERN = "[%s] %s: %s";
	private static final String CLIENT_INFO_MSG_TOO_LONG_MESSAGE = "Message is too long. Maximum message length is %d.";

	public SendMessageCommand() {
		super("msg", 1);
	}

	@Override
	public void executeAuthorized(final Client client, final String[] args) {
		String message = args[0];
		SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
		String date = dateTimeFormatter.format(Calendar.getInstance().getTime());
		
		try {
			validateLength(message, MAX_MESSAGE_LENGTH);
			client.getRoom().send(MESSAGE_PATTERN, date, client.getName(), message);
		} catch (InvalidArgumentException e) {
			client.send(CLIENT_INFO_MSG_TOO_LONG_MESSAGE, MAX_MESSAGE_LENGTH);
		}
	}
}
